/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.mobile.econsole.modules.apps.service.impl.AppInfoServiceImpl.java 
 * <p>
 * 类产生时间: 2014/4/29 0029 下午 22:27
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 掌上公安应用平台
 * <p>
 * 所在部门: 开发部--手持技术部
 * <p>
 * <p>
 */
package com.oceansoft.mobile.econsole.modules.apps.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.oceansoft.mobile.econsole.cache.redis.CacheBaseService;
import com.oceansoft.mobile.econsole.common.util.FileUtils;
import com.oceansoft.mobile.econsole.common.util.web.PageUtil;
import com.oceansoft.mobile.econsole.modules.apps.entity.*;
import com.oceansoft.mobile.econsole.modules.apps.persistence.IAppInfoMapper;
import com.oceansoft.mobile.econsole.modules.apps.persistence.IAppVersionMapper;
import com.oceansoft.mobile.econsole.modules.apps.persistence.IMenuMsgMapper;
import com.oceansoft.mobile.econsole.modules.apps.service.IAppInfoService;
import com.oceansoft.mobile.econsole.modules.base.entity.Pager;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: Administrator
 * @time: 2014/4/29 0029 下午 22:27
 */
@Service
public class AppInfoServiceImpl extends CacheBaseService implements IAppInfoService {

    @Resource
    private IAppInfoMapper appInfoMapper;

    @Resource
    private IMenuMsgMapper menuMsgMapper;

    @Resource
    private IAppVersionMapper versionMapper;

    @Override
    public Pager<AppInfo> findByPage(Query query) {
        PageHelper.startPage(query.getPageNum(), query.getNumPerPage(), true);
        return PageUtil.page2pager((Page<AppInfo>) appInfoMapper.loadPageByCondition(query), query);
    }

    @Override
    public AppInfo findAppInfoById(int appId) {
        return appInfoMapper.findAppInfoById(appId);
    }

    public AppInfo findAppBaseInfoById(int appId) {
        AppInfo appInfo = appInfoMapper.findAppBaseInfoById(appId);
        if (null != appInfo) {
            appInfo.setVersionGroups(versionMapper.loadVersionHistory(appInfo.getId()));
        }
        return appInfo;
    }

    @Override
    public List<AppInfo> findPageForApp(int pageSize, int pageIndex, String hostIP) {
        PageHelper.startPage(pageIndex, pageSize, false);
        List<AppInfo> list = appInfoMapper.findAppsListByPage(new Query(pageSize, pageIndex));
        if (null == list)
            return null;
/*        for (AppInfo info : list) {
            //处理插件内容
            blobHandle(info.getAppContent(), info.getUrl(), hostIP);
            //处理图标内容
            blobHandle(info.getIconContent(), info.getIcon(), hostIP);
            info.setVersionGroups(versionMapper.loadVersionHistory(info.getId()));
            info.setImgPath(configInfo);
            if (StringUtils.hasText(info.getIcon()))
                info.setIcon(configInfo.getResourceDownloadUrl(info.getIcon()));
            if (StringUtils.hasText(info.getUrl()))
                info.setUrl(configInfo.getResourceDownloadUrl(info.getUrl()));
            info.setAppContent(null);
            info.setIconContent(null);
        }*/
        return list;
    }

    private void blobHandle(byte[] bytes, String url, String hostIP) {
        if (StringUtils.isEmpty(url))
            return;
        if (null == bytes)
            return;
        String[] arr = url.split("/");
        File file = new File(configInfo.getUploadSubDir(url));
        if (!file.exists()) {
            try {
                File newFile = FileUtils.createFile(FileUtils.makeDir(configInfo.getUploadSubDir(arr[0])), arr[1]);
                FileUtils.createFile(new ByteArrayInputStream(bytes), newFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Message findMessageByMenuId(int menuId) {
        Message msg = new Message();
        List<MenuMsg> list = menuMsgMapper.findMessagesByMenuId(menuId);
        if (list.size() > 0) {
            msg.setHead(list.get(0));
            list.remove(0);
        }
        msg.setBody(list);
        msg.setTime(System.currentTimeMillis());
        return msg;
    }
    
    @Override
    public void insertAppDownload(AppDownload appdownload){
    	appInfoMapper.insertAppDownload(appdownload);
    	
    }
    
    
    

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Result deleteAppById(int appId) {
        AppInfo info = appInfoMapper.findAppInfoById(appId);
        if (null != info) {
            //FIXME:采用NFS文件共享，此处不用smb协议。下面现行代码需要修改
//            com.oceansoft.mobile.econsole.common.util.FileUtils.smbDelete(configInfo.getSmbFolder(info.getUrl()));
//            com.oceansoft.mobile.econsole.common.util.FileUtils.smbDelete(configInfo.getSmbFolder(info.getIcon()));
            appInfoMapper.deleteById(appId);
            return new Result();
        }
        return new Result(Result.FAILURE, "插件未找到");
    }

    private byte[] getBlobBytes(String url, String hostIP) {
        if (StringUtils.isEmpty(url))
            return null;
        byte[] bytes = null;
        File file = null;
        int size = 0;
        String fileUrl = configInfo.getUploadSubDir(url);
        file = new File(fileUrl);
        //FIXME:此处修改为NFS存储，无需判断IP，故测试结束后应删除注释行
//        if (hostIP.equals(configInfo.getFileServerHost())) {
//            file = new File(fileUrl);
//        } else {
//            String fileStr = FileUtils.smbGet(configInfo.getSmbFolder(url), Constant.getTempDir());
//            if (StringUtils.isEmpty(fileStr))
//                return null;
//            file = new File(FileUtils.smbGet(configInfo.getSmbFolder(url), Constant.getTempDir()));
//        }
        try {
            if (file.exists()) {
                size = (int) file.length();
                bytes = new byte[size];
                FileInputStream inputStream = new FileInputStream(file);
                inputStream.read(bytes);
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

    @Override
    @Transactional
    public Result save(AppInfo appInfo, String hostIP) {
        byte[] contentBytes = getBlobBytes(appInfo.getUrl(), hostIP);
        byte[] iconBytes = getBlobBytes(appInfo.getIcon(), hostIP);
        appInfo.setToken("");
        appInfo.setSnapImg("");
        appInfo.setAppType("1");
        if(org.apache.commons.lang.StringUtils.isBlank(appInfo.getStartPage())){
            appInfo.setStartPage("");
        }
        if (null != contentBytes) {
            appInfo.setAppSize(contentBytes.length);
            appInfo.setAppContent(contentBytes);
        } else {
            appInfo.setAppSize(0);
            appInfo.setAppContent(null);
        }
        if (null != iconBytes)
            appInfo.setIconContent(iconBytes);
        else
            appInfo.setIconContent(null);
        appInfoMapper.save(appInfo);
        return new Result(appInfo);
    }

    @Override
    public Result save(AppVersion appVersion) {
        versionMapper.save(appVersion);
        return new Result(appVersion);
    }

    @Override
    @Transactional
    public Result update(AppInfo appInfo, String hostIP) {
        byte[] contentBytes = getBlobBytes(appInfo.getUrl(), hostIP);
        byte[] iconBytes = getBlobBytes(appInfo.getIcon(), hostIP);

        if (null != contentBytes) {
            appInfo.setAppSize(contentBytes.length);
            appInfo.setAppContent(contentBytes);
        }

        if (null != iconBytes)
            appInfo.setIconContent(iconBytes);

        appInfoMapper.update(appInfo);
        return new Result();
    }

    @Override
    public Result loadAppVersionInfo() {
        AppInfo app = appInfoMapper.findAppBaseInfoById(0);
        if (null != app)
            return new Result(Result.SUCC, app);
        return new Result(Result.FAILURE, "暂无数据");
    }

    @Override
    public Result findDefaultAppPlugins() {
        List<AppInfo> list = appInfoMapper.findDefaultPlugins();
        if (null != list && list.size() > 0) {
            for (AppInfo info : list) {
                info.setVersionGroups(versionMapper.loadVersionHistory(info.getId()));
                info.setImgPath(configInfo);
                if (StringUtils.hasText(info.getIcon()))
                    info.setIcon(configInfo.getResourceDownloadUrl(info.getIcon()));
                if (StringUtils.hasText(info.getUrl()))
                    info.setUrl(configInfo.getResourceDownloadUrl(info.getUrl()));
            }
            return new Result(Result.SUCC, list);
        }
        return new Result(Result.FAILURE, "暂无数据");
    }

	@Override
	public List<AppInfoV2> findPageForAppV2(int pageSize, int pageIndex,
			String hostIP) {
	   PageHelper.startPage(pageIndex, pageSize, false);
       List<AppInfoV2> list = appInfoMapper.findAppsListByPageV2(new Query(pageSize, pageIndex));
       if (null == list)
           return null;
       for (AppInfoV2 info : list) {
           info.setUrl(info.getUrl()==null?"":info.getUrl());
           if (StringUtils.hasText(info.getIcon()))
               info.setIcon(configInfo.getResourceDownloadUrl(info.getIcon()));
       }
       return list;
	}
}
